const ITEM_LIST_KEY = 'itemList'
export const defaultItems = [
  {
    name: 'item1',
    weight: 18,
    address: 'New York No. 1 Lake Park'
  },
  {
    name: 'item2',
    weight: 24,
    address: 'London No. 1 Lake Park'
  }
]

export const list = () => {
  const list = localStorage.getItem(ITEM_LIST_KEY)
  if (list) {
    return JSON.parse(list)
  }
  return list
}

export const save = newItem => {
  let list = localStorage.getItem(ITEM_LIST_KEY)
  if (list) {
    list = JSON.parse(list)
  } else {
    list = []
  }
  let find = list.find(item => item.name === newItem.name)
  if (find) {
    list.splice(list.findIndex(item => item.name === find.name), 1)
  }
  list.push(newItem)
  localStorage.setItem(ITEM_LIST_KEY, JSON.stringify(list))
}

export const remove = name => {
  let list = localStorage.getItem(ITEM_LIST_KEY)
  if (list) {
    list = JSON.parse(list)
  } else {
    list = []
  }
  list.splice(list.findIndex(item => item.name === name), 1)
  localStorage.setItem(ITEM_LIST_KEY, JSON.stringify(list))
}
